/**
 * Change the url value according to the path specified
 * in the URL. Make the AJAX callback an event handler that detects clicks
 * and changes the 'url' to that of the current location.href if it's a local
 * path.
 * TODO(paakwesi) : Update the breadcrumb div with the current menu path.
 *                  Need to implement a special callback that generates
 *                  a string version of the breadcrumb when given a menu path
 */ 
$(document).ready (function() { 
 //but what if someone just lands on a jsviewer page?
 //let's create a hidden a href and trigger a click on it
 var initpath = Drupal.settings.basePath+location.hash.replace('#', '');
 $('#kjson').html("<a href='"+initpath+"'>" +
                  Drupal.t('Redirecting you to @path', {'@path': initpath}) +
                  "</a>");
 initializelinks('');
 $('#kjson a').triggerHandler('click'); //Now simulate a click
});

var pageHandler = function(data) {
  if(data == 3) {
    data = Drupal.t('<h2>Access denied</h2>');
  }else if(data == 4) {
    data = Drupal.t('<h2>Page not found</h2>');
  }
  $('#kjson').html(data);
/*var $dialog = $('<div></div>')
		.html('This dialog will show every time!')
		.dialog({
			autoOpen: false,
			title: 'Basic Dialog'
		});*/
  initializelinks('kjson');
  return false;
}

var clickHandler = function(e){
  var thispageHandler = function(data) {alert('yo');};
  var path = this.href.substring(this.href.indexOf('jsviewer#'));
  path = path.replace('jsviewer#', 'js/');
  $.get(path, pageHandler); 
  //Update other sections of the page that should be refreshed after a click
  //updatesections(location.hash);
}


function initializelinks(div_id){
  var div = '';
  if(div_id){
    div = '#' + div_id + ' ';
  }
  //change the url of every <a> tag
  $(div+'a').attr('href', function (arr) {
      return this.href.replace(Drupal.settings.basePath,
          Drupal.settings.basePath + 'jsviewer#' );
  });
  //And then bind the click event handler
  $(div+'a').unbind('click');
  $(div+'a').bind('click', clickHandler);
}

/**
 *Update breadcrumbs, messages, blocks divs
 */
function updatesections(path) {
   //TODO: complete
   return;
  //$('.breadcrumb').html(path);
  $.ajax({
    url: Drupal.settings.basePath + 'jsmessages',
    success: function(data){
      alert(data);
    },
    dataType: 'json'
  });
  $('.messages').hide();
  $('.messages').fadeIn('slow');
}
